<template>
  <div class="user-management">
    <div class="header">
      <h1>用户管理</h1>
      <div class="actions">
        <el-input
          v-model="searchName"
          placeholder="请输入真实姓名搜索"
          style="width: 200px; margin-right: 10px;"
          @keyup.enter="searchUsers"
        />
        <el-button type="primary" @click="searchUsers">搜索</el-button>
        <el-button type="success" @click="showAddDialog">添加用户</el-button>
      </div>
    </div>

    <!-- 用户列表表格 -->
    <el-table
      :data="filteredUsers"
      stripe
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="userName" label="用户名" width="120" />
      <el-table-column prop="realName" label="真实姓名" width="120" />
      <el-table-column label="用户类型" width="100">
        <template #default="scope">
          {{ getUserTypeText(scope.row.useType) }}
        </template>
      </el-table-column>
      <el-table-column label="所在科室" width="120">
        <template #default="scope">
          {{ getDeptName(scope.row.deptID) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            @click="showEditDialog(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="deleteUser(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      @close="resetForm"
    >
      <el-form
        :model="userForm"
        :rules="formRules"
        ref="userFormRef"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="userForm.userName" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="userForm.realName" />
        </el-form-item>
        <el-form-item label="用户类型" prop="useType">
          <el-select v-model="userForm.useType" placeholder="请选择用户类型">
            <el-option
              v-for="item in userTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所在科室" prop="deptID">
          <el-select v-model="userForm.deptID" placeholder="请选择科室">
            <el-option
              v-for="dept in departments"
              :key="dept.id"
              :label="dept.deptName"
              :value="dept.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'UserManagement',
  setup() {
    const loading = ref(false)
    const searchName = ref('')
    const dialogVisible = ref(false)
    const dialogTitle = ref('添加用户')
    const isEdit = ref(false)
    
    // 静态用户数据，基于后端表数据
    const users = ref([
      {
        id: 1,
        userName: 'admin',
        password: 'admin123',
        realName: '系统管理员',
        useType: 1,
        deptID: 9,
        docTitleID: null,
        isScheduling: '否',
        registLeID: null,
        delMark: 1
      },
      {
        id: 12,
        userName: 'user1',
        password: 'admin123',
        realName: 'zhangsan',
        useType: 2,
        deptID: 1,
        docTitleID: null,
        isScheduling: null,
        registLeID: null,
        delMark: 1
      },
      {
        id: 13,
        userName: 'user2',
        password: 'admin123',
        realName: 'lisi',
        useType: 2,
        deptID: 2,
        docTitleID: null,
        isScheduling: null,
        registLeID: null,
        delMark: 1
      },
      {
        id: 14,
        userName: 'doc001',
        password: '123456',
        realName: '张医生',
        useType: 3,
        deptID: 1,
        docTitleID: null,
        isScheduling: '是',
        registLeID: null,
        delMark: 1
      },
      {
        id: 15,
        userName: 'doc002',
        password: '123456',
        realName: '李医生',
        useType: 3,
        deptID: 2,
        docTitleID: null,
        isScheduling: '是',
        registLeID: null,
        delMark: 1
      },
      {
        id: 16,
        userName: 'doc003',
        password: '123456',
        realName: '王主任',
        useType: 3,
        deptID: 1,
        docTitleID: null,
        isScheduling: '是',
        registLeID: null,
        delMark: 1
      }
    ])

    // 下一个用户ID，用于添加新用户
    const nextUserId = ref(17)

    const departments = ref([
      { id: 1, deptName: '内科' },
      { id: 2, deptName: '外科' },
      { id: 3, deptName: '妇科' },
      { id: 4, deptName: '儿科' },
      { id: 5, deptName: '眼科' },
      { id: 6, deptName: '耳鼻喉科' },
      { id: 7, deptName: '放射科' },
      { id: 8, deptName: '检验科' },
      { id: 9, deptName: '药房' }
    ])

    const userTypes = ref([
      { value: 1, label: '管理员' },
      { value: 2, label: '挂号员' },
      { value: 3, label: '医生' }
    ])

    // 用户表单
    const userForm = reactive({
      id: null,
      userName: '',
      password: '',
      realName: '',
      useType: null,
      deptID: null,
      isScheduling: null,
      registLeID: null,
      docTitleID: null,
      delMark: 1
    })

    // 表单验证规则
    const formRules = {
      userName: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
      ],
      realName: [
        { required: true, message: '请输入真实姓名', trigger: 'blur' }
      ],
      useType: [
        { required: true, message: '请选择用户类型', trigger: 'change' }
      ],
      deptID: [
        { required: true, message: '请选择科室', trigger: 'change' }
      ]
    }

    const userFormRef = ref(null)

    // 过滤已删除的用户和搜索条件
    const filteredUsers = computed(() => {
      let result = users.value.filter(user => user.delMark === 1)
      
      if (searchName.value) {
        result = result.filter(user => 
          user.realName.toLowerCase().includes(searchName.value.toLowerCase())
        )
      }
      
      return result
    })

    // 获取用户类型文本
    const getUserTypeText = (useType) => {
      const type = userTypes.value.find(t => t.value === useType)
      return type ? type.label : '未知'
    }

    // 获取科室名称
    const getDeptName = (deptID) => {
      const dept = departments.value.find(d => d.id === deptID)
      return dept ? dept.deptName : '未知科室'
    }

    // 搜索用户（静态实现）
    const searchUsers = () => {
      // 由于使用了computed属性，这里只需要触发一下更新
      ElMessage.success('搜索完成')
    }

    // 显示添加对话框
    const showAddDialog = () => {
      dialogTitle.value = '添加用户'
      isEdit.value = false
      dialogVisible.value = true
    }

    // 显示编辑对话框
    const showEditDialog = (user) => {
      dialogTitle.value = '编辑用户'
      isEdit.value = true
      Object.assign(userForm, { ...user })
      dialogVisible.value = true
    }

    // 重置表单
    const resetForm = () => {
      Object.assign(userForm, {
        id: null,
        userName: '',
        password: '',
        realName: '',
        useType: null,
        deptID: null,
        isScheduling: null,
        registLeID: null,
        docTitleID: null,
        delMark: 1
      })
      if (userFormRef.value) {
        userFormRef.value.resetFields()
      }
    }

    // 提交表单（静态实现）
    const submitForm = async () => {
      if (!userFormRef.value) return

      await userFormRef.value.validate(async (valid) => {
        if (valid) {
          loading.value = true
          
          // 模拟API延迟
          setTimeout(() => {
            try {
              if (isEdit.value) {
                // 编辑用户
                const index = users.value.findIndex(u => u.id === userForm.id)
                if (index !== -1) {
                  users.value[index] = { ...userForm }
                  ElMessage.success('用户更新成功')
                }
              } else {
                // 添加用户
                const newUser = {
                  ...userForm,
                  id: nextUserId.value++
                }
                users.value.push(newUser)
                ElMessage.success('用户添加成功')
              }
              
              dialogVisible.value = false
            } catch (error) {
              ElMessage.error('操作失败')
              console.error(error)
            } finally {
              loading.value = false
            }
          }, 500)
        }
      })
    }

    // 删除用户（静态实现）
    const deleteUser = async (user) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除用户 "${user.realName}" 吗？`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        loading.value = true
        
        // 模拟API延迟
        setTimeout(() => {
          const index = users.value.findIndex(u => u.id === user.id)
          if (index !== -1) {
            // 软删除，将delMark设为0
            users.value[index].delMark = 0
            ElMessage.success('删除成功')
          }
          loading.value = false
        }, 300)
        
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
          console.error(error)
        }
      }
    }

    // 登出
    const logout = async () => {
      try {
        ElMessage.success('登出成功')
        // 这里可以跳转到登录页面
        // window.location.href = '/login'
        console.log('跳转到登录页面')
      } catch (error) {
        ElMessage.error('登出失败')
        console.error(error)
      }
    }

    onMounted(() => {
      // 静态版本不需要初始化数据
      ElMessage.success('用户管理系统加载完成')
    })

    return {
      loading,
      searchName,
      dialogVisible,
      dialogTitle,
      isEdit,
      users,
      filteredUsers,
      departments,
      userTypes,
      userForm,
      formRules,
      userFormRef,
      getUserTypeText,
      getDeptName,
      searchUsers,
      showAddDialog,
      showEditDialog,
      resetForm,
      submitForm,
      deleteUser,
      logout
    }
  }
}
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h1 {
  margin: 0;
  color: #333;
}

.actions {
  display: flex;
  align-items: center;
}

.dialog-footer {
  text-align: right;
}
</style>